#!/usr/bin/perl
# 2014/05/15 count common associations

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 8 or $ARGV[0] eq '--help'){
	die "Usage : $0 -a [peak summit fileA] -b [peak summit fileB] -c [association fileA] -d [association fileB]\n";
}


my $SERACH_RANGE = 2000;

my %opt;
getopts("a:b:c:d:", \%opt);
my $FILE_summitA = $opt{a};
my $FILE_summitB = $opt{b};
my $FILE_asoA = $opt{c};
my $FILE_asoB = $opt{d};

my $PEKAS_A = 0;
my %A_name;
my $fh_summitA = IO::File->new($FILE_summitA) or die "cannot open $FILE_summitA: $!";
while($_ = $fh_summitA->getline()){
	s/\r?\n//;
	$PEKAS_A++;
	my ($chr, $start, $end, $name, $score) = split /\t/;
	$start -= 1500;
	$end = $start + 2999;
	for(my $i = $start - $SERACH_RANGE; $i <= $end + $SERACH_RANGE; $i++){
		push @{$A_name{$chr}{$i}}, $name;
	}
}
$fh_summitA->close();

my $PEKAS_B = 0;
my %B2A;
my $fh_summitB = IO::File->new($FILE_summitB) or die "cannot open $FILE_summitB: $!";
while($_ = $fh_summitB->getline()){
	s/\r?\n//;
	$PEKAS_B++;
	my ($chr, $start, $end, $name, $score) = split /\t/;
	$start -= 1500;
	$end = $start + 2999;
	my $peakA_name = '';
	my %nameList;
	for(my $i = $start; $i <= $end; $i++){
		if(exists $A_name{$chr}{$i}){
			foreach my $key(@{$A_name{$chr}{$i}}){
				$nameList{$key} = 1;
			}
		}
	}
	foreach my $key(keys %nameList){
		push @{$B2A{$name}}, $key;
	}
}
$fh_summitB->close();


#---------------------------------------
# count overlap of binding sites
#---------------------------------------
my $COMMON_binding = 0;
foreach my $key(keys %B2A){
	$COMMON_binding++;
}
print "Binding A:\t$PEKAS_A\n";
print "Binding B:\t$PEKAS_B\n";
print "Common :\t$COMMON_binding\n";


my $ASO_A = 0;
my %A_aso;
my $fh_asoA = IO::File->new($FILE_asoA) or die "cannot open $FILE_asoA: $!";
while($_ = $fh_asoA->getline()){
	s/\r?\n//;
	my ($name1, $loc1, $name2, $loc2, $interaction, $pval) = split /\t/;
	if($interaction == 1){
		next;
	}
	$ASO_A++;
	$A_aso{"$name1\t$name2"} = 1;
}
$fh_asoA->close();


my $COMMON_asociation = 0;
my $ASO_B = 0;
my $fh_asoB = IO::File->new($FILE_asoB) or die "cannot open $FILE_asoB: $!";
while($_ = $fh_asoB->getline()){
	s/\r?\n//;
	my ($name1, $loc1, $name2, $loc2, $interaction, $pval) = split /\t/;
	if($interaction == 1){
		next;
	}
	$ASO_B++;
	my @name1_inAs;
	my @name2_inAs;

	if(exists $B2A{$name1}){
		push @name1_inAs, @{$B2A{$name1}};
	}
	if(exists $B2A{$name2}){
		push @name2_inAs, @{$B2A{$name2}};
	}


	my $flag_found = 0;
	foreach my $t1(@name1_inAs){
		foreach my $t2(@name2_inAs){
			if((exists $A_aso{"$t1\t$t2"}) or (exists $A_aso{"$t2\t$t1"})){
				$flag_found = 1;
			}
		}
	}

	if($flag_found == 1){
		$COMMON_asociation++;
	}

}
$fh_asoB->close();

print "Association A (>1):\t$ASO_A\n";
print "Association B (>1):\t$ASO_B\n";
print "Common:\t$COMMON_asociation\n";
